﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace IEMSOFT.Foundation.MVC
{
    public class FromJsonAttribute : CustomModelBinderAttribute
    {
        public override IModelBinder GetBinder()
        {
            return new JsonModelBinder();
        }

        private class JsonModelBinder : IModelBinder
        {
            public object BindModel(ControllerContext ctx, ModelBindingContext bCtx)
            {
                var request = ctx.HttpContext.Request;
                byte[] byts = new byte[request.InputStream.Length];
                request.InputStream.Read(byts, 0, byts.Length);
                string req = System.Text.Encoding.UTF8.GetString(byts);
                if (string.IsNullOrEmpty(req))
                    return null;
                var model = JsonConvert.DeserializeObject(req, bCtx.ModelType);
                return model;
            }
        }
    }
}
